package com.raise.drive.web.controller;

import org.springframework.web.servlet.mvc.AbstractWizardFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.validation.BindException;
import com.raise.drive.model.service.UserService;
import com.raise.drive.model.service.SearchService;
import com.raise.drive.model.domain.Instructor;
import com.raise.drive.web.form.InstructorForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.HashMap;

/**
 * @author Eugene Rozov
 */
public class RegisterInstructorController extends AbstractWizardFormController {

    private UserService userService;

    private SearchService searchService;

    private String successView;

    private String cancelView;

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
//        binder.registerCustomEditor(Doctor.class, new DoctorBinder(doctorService));
//        binder.registerCustomEditor(Date.class, new DatePropertyEditor(Utils.getDateFormat(request)));
    }

    @Override
    protected Map<String, Object> referenceData(HttpServletRequest request, int page) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();

        if (page == 1) {
            result.put("carVendors", searchService.getAllCarVendors());
        }

        return result;
    }

    @Override
    protected ModelAndView processFinish(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
        InstructorForm form = (InstructorForm) command;
        Instructor instructor = form.getInstructor();
        instructor.getVehicles().add(form.getVehicle());
        for (int i = 0; i < InstructorForm.MAX_ADITIONAL_CARS; i++)  {
            if (form.getUsedVehicle()[i]) {
                instructor.getVehicles().add(form.getAdditionalVehicles().get(i));
            }
        }
        userService.registerInstructor(form.getInstructor());
        return new ModelAndView(successView);
    }

    @Override
    protected ModelAndView processCancel(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
        return new ModelAndView(cancelView);
    }


    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setSuccessView(String successView) {
        this.successView = successView;
    }

    public void setCancelView(String cancelView) {
        this.cancelView = cancelView;
    }

    public void setSearchService(SearchService searchService) {
        this.searchService = searchService;
    }
}
